#!/bin/bash
# Caline Second Instance — starts the installed CÂLINE DEV app as an
# independent second client (own login/session, windowed). Generated by
# tauri/scripts/release/mac-second-instance.py.
WANT="dev"
DEV_URL="https://dev.caline.ca"
PB=/usr/libexec/PlistBuddy

is_target() { # <bin>
  if grep -qaF "$DEV_URL" "$1" 2>/dev/null; then [ "$WANT" = dev ]; else [ "$WANT" = live ]; fi
}

BIN=""
while IFS= read -r app; do
  [ -f "$app/Contents/Info.plist" ] || continue
  [ "$("$PB" -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist" 2>/dev/null)" = "ca.caline.app" ] || continue
  exe="$("$PB" -c 'Print :CFBundleExecutable' "$app/Contents/Info.plist" 2>/dev/null)"
  [ -n "$exe" ] && [ -x "$app/Contents/MacOS/$exe" ] || continue
  if is_target "$app/Contents/MacOS/$exe"; then BIN="$app/Contents/MacOS/$exe"; break; fi
done < <(ls -d /Applications/*.app "$HOME"/Applications/*.app 2>/dev/null
         mdfind "kMDItemCFBundleIdentifier == 'ca.caline.app'" 2>/dev/null)

if [ -z "$BIN" ]; then
  /usr/bin/osascript -e 'display alert "CÂLINE DEV is not installed" message "Caline Second Instance starts a second copy of the CÂLINE DEV app. Download and install the main CÂLINE DEV app first, then open this again." as critical' >/dev/null 2>&1
  exit 1
fi

# Separate HOME keeps the app's own small data files (display mode, window
# size) apart from the main window's; CALINE_DS_ID keeps the web session apart.
DATA="$HOME/Library/Application Support/Caline Second Instance/dev"
mkdir -p "$DATA/home"
HOME="$DATA/home" \
CALINE_MULTI=1 \
CALINE_DS_ID=2 \
CALINE_TITLE="CÂLINE DEV — Second Instance" \
  "$BIN" >/dev/null 2>&1 &
wait $!
